package com.example.reggie.controller;

import com.example.reggie.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${common.basePath}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String originName=file.getOriginalFilename();
        String uuid= UUID.randomUUID().toString();
        String fileName=uuid+originName.substring(originName.lastIndexOf("."));
        File fileObj=new File(basePath);
        Boolean isExitsFolder=fileObj.exists();
        if (isExitsFolder==false){
            fileObj.mkdirs();
        }
        String filePath=basePath+fileName;
        File saveFile=new File(filePath);
        file.transferTo(saveFile);
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void download(ServletResponse response, String name) throws Exception {
        response.setContentType("image/png");
        File file=new File(basePath+name);
        if (!file.exists()){
            throw new RuntimeException("文件不存在");
        }
        FileInputStream fileInputStream=new FileInputStream(file);
        BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
        OutputStream outputStream = response.getOutputStream();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
        int num;
        byte[] bytes=new byte[1024];
        num = bufferedInputStream.read(bytes);
        while (num!=-1){
            bufferedOutputStream.write(bytes);
            num=bufferedInputStream.read(bytes);
        }
    }
}
